import 'dart:convert';

import 'package:e_reception_flutter/utils/vg_http_utils.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:vg_base/src/http/vg_http_response.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_pull_to_refresh_lib.dart';
import 'package:vg_base/vg_sp_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';

import 'common_list_page_widget.dart';

class CommonListPageViewModel<I, R extends BasePagerBean<I>>
    extends BasePagerViewModel<I, R> {
  bool needCache;
  String cacheKey;
  bool needCustomCache;
  final CommonListPageWidgetState state;

  CommonListPageViewModel(this.state,
      {this.needCache, this.cacheKey, this.needCustomCache})
      : super(state);

  @override
  Map<String, dynamic> getQuery(int page) {
    return state?.widget?.queryMapFunc?.call(page);
  }

  @override
  String getRequestMethod() {
    return state?.widget?.httpType?.getRequestMethod();
  }

  @override
  String getUrl() {
    return state?.widget?.netUrl ?? "";
  }

  @override
  R parseData(VgHttpResponse resp) {
    R vo = state?.widget?.parseDataFunc(resp);
    loading(false);
    if ((needCustomCache ?? false) && cacheKey != null && vo != null) {
      SharePreferenceUtil.putString(cacheKey, json.encode(vo));
    }
    return vo;
  }

  @override
  String getBodyData(int page) {
    return null;
  }

  @override
  bool isNeedCache() {
    return needCache ?? false;
  }

  @override
  String getCacheKey() {
    return cacheKey;
  }

  @override
  void refresh() {
    super.refresh();
    if (needCustomCache ?? false) {
      Future<String> future = SharePreferenceUtil.getString(cacheKey);
      future.then((jsonStr) {
        print(jsonStr);
        if (!StringUtils.isEmpty(jsonStr)) {
          try {
            Map map = json.decode(jsonStr);
            R data = parseData(
                VgHttpResponse(code: 200, message: map['msg'], data: map));
            if (data == null || !data.isSucceed()) {
              return;
            }
            // 获取到某个页面数据
            fullData.clear();
            List<I> dataList = data.getDataList();
            if (dataList == null) {
              return;
            }
            fullData.addAll(dataList);
            getDataChangeStreamController().add(fullData);
          } catch (e) {
            print(e.toString());
          }
        }
      });
    }
  }

  @override
  Stream<String> get onRefreshFailed => Stream.value(null);
}
